﻿using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using Caliburn.Micro;
using PocketBook.Model;
using PocketBook.Tasks;
using PocketBook.ViewModels.Events;

namespace PocketBook.ViewModels
{
    [Export(typeof(EditorViewModel))]
    public class EditorViewModel : Screen, IHandle<ActiveDesignChanged>
    {
        private readonly ILayoutMetrics _metrics;
        private IDesign _design;

        [ImportingConstructor]
        public EditorViewModel(IEventAggregator events, ILayoutMetrics layoutMetrics)
        {
            _metrics = layoutMetrics;
            events.Subscribe(this);
        }

        public Size SiteSize
        {
            get { return _metrics.SiteSize; }
        }

        public IDesign Design
        {
            get { return _design; }
            set
            {
                if (value == Design) return;

                _design = value;
                NotifyOfPropertyChange(() => Design);
            }
        }

        public void Handle(ActiveDesignChanged message)
        {
            Design = message.ActiveDesign;
        }

        public IEnumerable<IResult> Edit()
        {
            if (Design == null) yield break;
            var editorAttribute = (DesignEditorAttribute)(Design.GetType().GetCustomAttributes(typeof (DesignEditorAttribute), false)).FirstOrDefault();

            var editor = IoC.GetInstance(editorAttribute == null ? typeof(PropertyEditorViewModel) : editorAttribute.EditorType, string.Empty) as IDesignEditor;
            if (editor == null) yield break;

            var editableDesign = (IEditableObject)Design;
            editableDesign.BeginEdit();

            editor.Design = Design;

            var dialog = Show.Dialog(editor);
            dialog.Completed += (sender, args) =>
            {
                if (args.WasCancelled)   
                    editableDesign.CancelEdit();
                else
                    editableDesign.EndEdit();
            };

            yield return dialog;
        }
    }
}